import os
import sys
import subprocess
import platform
import re
from PyQt5.QtCore import QThread, pyqtSignal

class HardwareCheckThread(QThread):
    hardware_detected = pyqtSignal(dict)
    log_message = pyqtSignal(str)
    
    def __init__(self):
        super().__init__()
        self.ffmpeg_path = ""
        self.is_running = False
    
    def run(self):
        """运行硬件检测线程"""
        self.is_running = True
        
        try:
            self.log_message.emit("开始检测系统硬件加速支持情况...")
            
            # 检测FFmpeg
            if self.ffmpeg_path and os.path.exists(self.ffmpeg_path):
                self.log_message.emit(f"检测到FFmpeg: {self.ffmpeg_path}")
                
                # 检测FFmpeg支持的硬件加速
                hardware_info = {"cuda": False, "dxva2": False, "qsv": False, "d3d11va": False, "opencl": False, "vulkan": False}
                
                # 运行FFmpeg -hwaccels命令
                try:
                    result = subprocess.run([self.ffmpeg_path, "-hwaccels"], 
                                           capture_output=True, 
                                           text=True, 
                                           check=False)
                    
                    output = result.stdout + result.stderr
                    
                    # 检查各种硬件加速
                    if "cuda" in output.lower():
                        hardware_info["cuda"] = True
                        self.log_message.emit("FFmpeg支持硬件加速: cuda")
                    
                    if "dxva2" in output.lower():
                        hardware_info["dxva2"] = True
                        self.log_message.emit("FFmpeg支持硬件加速: dxva2")
                    
                    if "qsv" in output.lower():
                        hardware_info["qsv"] = True
                        self.log_message.emit("FFmpeg支持硬件加速: qsv")
                    
                    if "d3d11va" in output.lower():
                        hardware_info["d3d11va"] = True
                        self.log_message.emit("FFmpeg支持硬件加速: d3d11va")
                    
                    if "opencl" in output.lower():
                        hardware_info["opencl"] = True
                        self.log_message.emit("FFmpeg支持硬件加速: opencl")
                    
                    if "vulkan" in output.lower():
                        hardware_info["vulkan"] = True
                        self.log_message.emit("FFmpeg支持硬件加速: vulkan")
                    
                except Exception as e:
                    self.log_message.emit(f"检测FFmpeg硬件加速出错: {str(e)}")
            else:
                self.log_message.emit("未检测到FFmpeg，请在设置中指定FFmpeg路径")
                hardware_info = {}
            
            # 检测CUDA支持
            try:
                import torch
                if torch.cuda.is_available():
                    hardware_info["cuda"] = True
                    hardware_info["cuda_info"] = f"CUDA {torch.version.cuda}, {torch.cuda.get_device_name(0)}"
                    self.log_message.emit(f"检测到NVIDIA GPU，MiDaS可以使用CUDA加速")
            except:
                # 如果无法导入torch，尝试使用其他方法检测CUDA
                try:
                    if cv2.cuda.getCudaEnabledDeviceCount() > 0:
                        hardware_info["cuda"] = True
                        hardware_info["cuda_info"] = "CUDA支持通过OpenCV检测"
                        self.log_message.emit("检测到NVIDIA GPU，MiDaS可以使用CUDA加速")
                except:
                    pass
            
            # 发送硬件检测结果
            self.hardware_detected.emit(hardware_info)
            
        except Exception as e:
            self.log_message.emit(f"硬件检测出错: {str(e)}")
        
        self.is_running = False
    
    def set_ffmpeg_path(self, path):
        self.ffmpeg_path = path
    
    def detect_ffmpeg_acceleration(self, hardware_info):
        try:
            # 检查FFmpeg是否支持CUDA
            startupinfo = None
            if platform.system() == "Windows":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            
            result = subprocess.run(
                [self.ffmpeg_path, "-hide_banner", "-hwaccels"],
                capture_output=True,
                text=True,
                startupinfo=startupinfo
            )
            
            if result.returncode == 0:
                output = result.stdout
                # 解析支持的硬件加速
                for line in output.splitlines():
                    line = line.strip().lower()
                    if line and line != "hardware acceleration methods:":
                        hardware_info["ffmpeg"]["acceleration"].append(line)
                        self.log_message.emit(f"FFmpeg支持硬件加速: {line}")
            else:
                self.log_message.emit("检测FFmpeg硬件加速失败")
        except Exception as e:
            self.log_message.emit(f"检测FFmpeg硬件加速时出错: {str(e)}")
    
    def detect_cuda_support(self, hardware_info):
        try:
            # 检查是否有NVIDIA GPU并支持CUDA
            if platform.system() == "Windows":
                # 在Windows上使用nvidia-smi检测CUDA
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                
                try:
                    result = subprocess.run(
                        ["nvidia-smi"],
                        capture_output=True,
                        text=True,
                        startupinfo=startupinfo
                    )
                    
                    if result.returncode == 0:
                        hardware_info["midas"]["acceleration"].append("cuda")
                        self.log_message.emit("检测到NVIDIA GPU，MiDaS可以使用CUDA加速")
                except FileNotFoundError:
                    self.log_message.emit("未检测到NVIDIA GPU或CUDA驱动")
            else:
                # 在其他系统上可以添加相应的检测方法
                pass
        except Exception as e:
            self.log_message.emit(f"检测CUDA支持时出错: {str(e)}")